package com.atguigu.day04;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//死锁
public class pratice1 {
    private static Lock lockA = new ReentrantLock();
    private static Lock lockB = new ReentrantLock();

    public static void main(String[] args) {
        lockA.lock();
        new Thread(() -> {

            try {
                //拥有A锁
                System.out.println(Thread.currentThread().getName() + "拥有lockA锁,想要获得B锁");
                //线程睡眠几秒
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                lockB.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + "成功获得B锁");
                } finally {
                    lockB.unlock();
                }


            } finally {
                lockA.unlock();
            }

        }, "A").start();
//        new Thread(() -> {
//            synchronized (lockB)
//            {
//                //拥有B锁
//                System.out.println(Thread.currentThread().getName()+"拥有lockB锁,想要获得A锁");
//                //线程睡眠几秒
//                try {
//                    TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {throw new RuntimeException(e);}
//                synchronized (lockA){
//                    System.out.println(Thread.currentThread().getName()+"成功获得A锁");
//                }
//            }
//
//        }, "B").start();
        lockB.lock();
        new Thread(() -> {

            try {
                //拥有A锁
                System.out.println(Thread.currentThread().getName() + "拥有lockB锁,想要获得A锁");
                //线程睡眠几秒
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                lockA.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + "成功获得A锁");
                } finally {
                    lockA.unlock();
                }

            } finally {
                lockB.unlock();
            }
        },"B").start();
    }
}



